package com.openapi.protocol.decode.subPackageHandle.handle;

import com.openapi.data.JT808PackageData;
import com.openapi.data.JT808PushData;
import com.openapi.protocol.decode.subPackageHandle.hj212Stream.FileBitStreamCache;
import com.openapi.protocol.encode.PackageHj212;
import exsun.jt808.data.distribute_data.jsatl12.FileUploadFinishedRep;
import exsun.jt808.data.upload_data.Jt808EntityBase;
import exsun.jt808.data.upload_data.jsatl12.FileUploadFinished;
import exsun.jt808.data.util.parse.DecoderUtils;
import exsun.jt808.data.util.parse.HexStrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 文件上传完成消息
 */
public class FileUploadFinishedHandle {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadFinishedHandle.class);

    public static Jt808EntityBase decode(JT808PackageData packageData) {
        byte[] body = packageData.getBodyBuffers();
        FileUploadFinished data = new FileUploadFinished();
        int len = DecoderUtils.parseIntFromBytes(body, 0, 1);
        data.setDvo(packageData.dvo);
        data.setFne(DecoderUtils.parseStringFromBytes(body, 1, len));
        data.setFte(DecoderUtils.parseIntFromBytes(body, 1 + len, 1));
        data.setFse(DecoderUtils.parseIntFromBytes(body, 2 + len, 4));
        return data;
    }

    public static List<JT808PushData> response(FileUploadFinished data,String dvo) {
        Map<Integer, Integer> miss = FileBitStreamCache.getMissItems(data.getFne());
        FileUploadFinishedRep rep = new FileUploadFinishedRep();
        rep.devNo = dvo;
        rep.setFileName(data.getFne());
        rep.setFileType(data.getFte());
        rep.setFileSize(data.getFse());
        rep.setMiss(miss);

        JT808PushData body = PackageHj212.fileFinishedRepEncode(rep);
        logger.info("文件上传完成--应答消息体" + HexStrUtil.encodeHex(body.body) + " -应答文件名-"+ data.getFne() + " -缺包个数-" + miss.size());
        List<JT808PushData> list = new ArrayList<>();
        list.add(body);
        return list;
    }
}
